package tn.orange.canreminder;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import tn.orange.canreminder.adapter.OpinionAdapter;
import tn.orange.canreminder.exception.ArticleLengthException;
import tn.orange.canreminder.exception.MailNotFoundException;
import tn.orange.canreminder.model.Opinion;
import tn.orange.canreminder.model.Rate;
import tn.orange.canreminder.service.OpinionService;
import tn.orange.canreminder.service.OpinionServiceImp;
import tn.orange.canreminder.service.SubmitRate;
import tn.orange.canreminder.service.SubmitRateServiceImp;
import tn.orange.canreminder.utils.Utility;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RatingBar;

public class OpinionActivity extends Activity {

	private ListView listView;
	private RatingBar ratingBar;
	private EditText article;
	private int place_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.opinion);

		place_id = getIntent().getExtras().getInt("place_id");
		listView = (ListView) findViewById(R.id.list_opinion);
		ratingBar = (RatingBar) findViewById(R.id.ratingBar1);
		article = (EditText) findViewById(R.id.opinion_article);

		OpinionAsyncTask asyncTask = new OpinionAsyncTask();
		asyncTask.execute();

		Button button = (Button) findViewById(R.id.opinion_btn);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				SubmitOpinionAsyncTask asyncTask = new SubmitOpinionAsyncTask();
				asyncTask.execute();

			}
		});

	}

	private class OpinionAsyncTask extends AsyncTask<Void, Void, List<Opinion>> {
		private final ProgressDialog dialog = new ProgressDialog(
				OpinionActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Opinion> doInBackground(final Void... args) {

			List<Opinion> opinions = new ArrayList<Opinion>();
			OpinionService service = new OpinionServiceImp();
			try {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				opinions = service.getAllOpinions(place_id);

				// opinions = MockObject.getMockOpinions();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(false);
			}
			return opinions;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			showErrorDialog("Problème de connexion ");

		}

		// can use UI thread here
		protected void onPostExecute(final List<Opinion> opinions) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();

			}

			listView.setAdapter(new OpinionAdapter(OpinionActivity.this,
					opinions));
			Utility.setListViewHeightBasedOnChildren(listView);

		}

		private void showErrorDialog(String message) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					OpinionActivity.this).create();
			alertDialog.setTitle("Erreur");
			alertDialog.setMessage(message);
			alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			alertDialog.show();
		}
	}

	private class SubmitOpinionAsyncTask extends AsyncTask<Void, Void, Void> {
		int error = 0;
		private final ProgressDialog dialog = new ProgressDialog(
				OpinionActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final Void... args) {

			try {

				SharedPreferences preferences = PreferenceManager
						.getDefaultSharedPreferences(OpinionActivity.this);
				String mail = preferences.getString("listPref", "");
				if (mail.equals("")) {

					throw new MailNotFoundException();
				}
				if (article.getText().toString().length() < 8) {
					throw new ArticleLengthException();
				}
				SubmitRate submitRate = new SubmitRateServiceImp();
				OpinionService submitOpinion = new OpinionServiceImp();
				Rate rate = new Rate();
				rate.setMail(mail);
				float rating = ratingBar.getRating();
				rate.setRate(rating);
				rate.setPlace_id(place_id);

				Opinion opinion = new Opinion();
				opinion.setUsername(getUserName(mail));
				opinion.setPlace_id(place_id);
				opinion.setArticle(article.getText().toString());

				submitRate.submitRate(rate);
				submitOpinion.submitOpinion(opinion);
			} catch (ArticleLengthException e) {
				error = 2;
				cancel(false);
			} catch (MailNotFoundException e) {
				error = 1;
				cancel(false);

			} catch (Exception e) {
				// TODO Auto-generated catch block

			}
			return null;

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			// OpinionAsyncTask asyncTask2 = new OpinionAsyncTask();
			// asyncTask2.execute();
			finish();

		}

		private String getUserName(String mail) {
			String username = "";
			int pos = mail.indexOf("@");
			username = mail.substring(0, pos);
			return username;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			if (error == 1) {
				showErrorDialog("Veuillez taper votre mail");
				Intent intent = new Intent(OpinionActivity.this,
						ConfigActivity.class);
				startActivity(intent);
			} else if (error == 2) {
				showErrorDialog("Vous devez saisir au moins dix caracatères");
			} else
				showErrorDialog("Problème de connexion ");

		}

		private void showErrorDialog(String message) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					OpinionActivity.this).create();
			alertDialog.setTitle("Erreur");
			alertDialog.setMessage(message);
			alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			alertDialog.show();
		}

	}

	public void OnHomeClick(View v) {
		Intent intent = new Intent(getApplicationContext(),
				DashboardActivity.class);
		startActivity(intent);
	}
}
